//
//  HJComposeViewController.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/10/6.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit
import SVProgressHUD

class HJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        setTextView()
        setToolBar()
        registerNotification()
        setSelectedPicView()
        self.view.bringSubview(toFront: toolbar)
    }

    //图片视图将要显示的时候,就要把隐藏的selectePicVC.view 给显示出来
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if selectePicVC.images.count != 0 {
            selectePicVC.view.isHidden = false
        }
    }
    
    
    
   internal lazy var sendBtn : UIBarButtonItem = {
    
    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
    btn.setTitle("发送", for: .normal)
    
    //设置背景图片
    btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
    btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
    btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white"), for: .disabled)
    
    //设置文字颜色
    btn.setTitleColor(UIColor.darkGray, for: .disabled)
    btn.setTitleColor(UIColor.white, for: .normal)
    
    btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
    
    
    let barButtonItem = UIBarButtonItem(customView: btn)
    barButtonItem.isEnabled = false
    return barButtonItem
    }()
    
    
    internal lazy var textView : UITextView = {
        
        let textView = UITextView()
        textView.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
        textView.textColor = UIColor.darkGray
        textView.font = UIFont.systemFont(ofSize: 16)
        
        //设置代理
        textView.delegate = self
        
        //设置键盘隐藏的方式  早期的滚动视图中包含了文本输入框,需要隐藏键盘的时候可以在滚动视图的代理方法中实现取消第一响应者的方法
        
        //Mark: 第一种方法
        //tv.keyboardDismissMode = .onDrag
        //开启垂直方向可以滚动
        
        //第二种方法使用代理
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    //设置占位文本
    internal lazy var placeHolderLable = UILabel(title: "听说明天是S6小组赛的第二轮", textColor: UIColor.lightGray, fontSize: 16)
    
    //图片选择视图
    lazy var selectePicVC : HJPicSelectViewController = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = selectCellMargin
        layout.minimumInteritemSpacing = selectCellMargin
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: selectCellMargin, left: selectCellMargin, bottom: 0, right: selectCellMargin)
        let selectedVC = HJPicSelectViewController(collectionViewLayout: layout)
        selectedVC.collectionView?.backgroundColor = UIColor.white
        return selectedVC
    }()
    
    
    
    
    //通知
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    func keyboardWillChange(notification : Notification) {
        //自定义中不能直接存放结构体
        let endFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        //更改toolbar的约束
        let offsetY = -KScreenH + endFrame.origin.y
        toolbar.snp.updateConstraints { (make) in
            
            make.bottom.equalTo(offsetY)
        }
        
        //添加动画
        UIView.animate(withDuration: 0.5) { 
            self.view.layoutIfNeeded()
        }
    }
    
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //设置底部工具条
    internal lazy var toolbar : UIToolbar = {
        let tool = UIToolbar()
        var items = [UIBarButtonItem]()
        
        //添加五个按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for value in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named:value.element), for: .normal)
            btn.setImage(UIImage(named: value.element + "_highlighted"), for: .highlighted)
            
            //设置索引
            btn.tag = value.offset
            //添加点击事件
            btn.addTarget(self, action: #selector(statueTypeBtnDidClick(btn: )), for: .touchUpInside)
            btn.sizeToFit()
            
            let barItem = UIBarButtonItem(customView: btn)
            
            items.append(barItem)
            
            //添加等宽弹簧
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        tool.items = items
        
        return tool
    }()
    
    
    @objc internal func statueTypeBtnDidClick(btn: UIButton){
        switch btn.tag {
        case 0:
            print("发布图片")
            //手动添加图片
            selectePicVC.userWillAddPic()
        case 1:
            print("@某人")
        case 2:
            print("发布话题")
        case 3:
            print("发布表情")
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            textView.inputView = (textView.inputView == nil ? keyboardView : nil)
            
            textView.reloadInputViews()
            
        case 4:
            print("更多")
        
        default:
            print("瞎点")
        }
    }
    
    //表情键盘属性声明
    lazy var keyboardView: HJEmoticonKeyboardView = {
        //在iPhone plus类型的设备上键盘的高度 是226 其他的设备都是216
        let keyboard = HJEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: emoticonKeyboardHeight))
        
        return keyboard
    }()

    
    
    
    
    //sendBtn的点击事件
   @objc internal func sendBtnDidClick() {
    
    var urlString = "https://api.weibo.com/2/statuses/update.json"
    
    //在数组中不能直接添加隐式的可选类型
    let parameters = ["access_token" : HJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token ?? "" ,
                      "status" : textView.text ?? "" ]
    
    //判断是文本微博还是图片微博
    if selectePicVC.images.count == 0  {
        //文本微博
        HJNetworkTools.sharedTool.request(method: .POST, urlString: urlString, parameters: parameters) { (_, error) in
            
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
        }
    }else {
        //图片微博
         urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        HJNetworkTools.sharedTool.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
            //需要将上传的二进制文件拼接到formdata

            //上传一张
            let imageData = UIImagePNGRepresentation(self.selectePicVC.images.last!)
            
            /*
            withFileData  需要上传文件的二进制数据
            name : 服务器接收的字段  要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
            3. fileName: 服务器存储的名称  传或者不传 无所谓 新浪微博有自己的一套文件命名规则
            4. mimeType 上传的文件的类型  application/octet-stream 忽略文件类型
            */
            
            formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "xhj", mimeType: "application/octet-stream")
            
 
            }, progress: nil, success: { (_, _) in
                SVProgressHUD.showSuccess(withStatus: "发布图片微博成功")
            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
        })
    }
    
    
    }
}



extension HJComposeViewController:UITextViewDelegate {
    //文本输入框一旦产生变化就得到响应
    func textViewDidChange(_ textView: UITextView) {
        //当文本框发生变化是就设置sendBtn为可用状态
        self.sendBtn.isEnabled = textView.hasText
        
        self.placeHolderLable.isHidden = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}







//Mark:设置UI界面
extension HJComposeViewController {
    
   internal func setNavBar() {
    
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",  target: self, action: #selector(close))
    
    //自定义titleView
    let titleLable = UILabel(title: "", textColor: UIColor.darkGray, fontSize: 16)
    var titleText = "发布微博"
    titleLable.numberOfLines = 0
    titleLable.textAlignment = .center
    
    if let name = HJUserAccountViewModel.sharedAccountViewModel.userAccount?.name
    {
        titleText = "发布微博\n\(name)"
        //通过富文本修改字体的大小和颜色
        //1.实例化一个可变的属性文本,只有是可变的才能添加属性
        let strM = NSMutableAttributedString(string: titleText)
        //获取范围
        let range = (titleText as NSString).range(of: name)
        
        //给可变的属性字符串添加属性
        strM.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13) , NSForegroundColorAttributeName : UIColor.orange], range: range)
        
        //设置属性字符串(将设置好的富文本赋给titleLable)
        titleLable.attributedText = strM
    }else {
        //为空  设置一个相同属性的文字即可
        titleLable.text = titleText
    }
    titleLable.sizeToFit()
    self.navigationItem.titleView = titleLable
    
    self.navigationItem.rightBarButtonItem = sendBtn
    
    }

    //dismiss控制器
    @objc internal func close() {
        dismiss(animated: true, completion: nil)
    }
    
    internal func setTextView() {
        self.view.addSubview(textView)
        
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(KScreenH/3)
        }
        
        self.textView.addSubview(placeHolderLable)
        placeHolderLable.snp.makeConstraints { (make) in
            
            make.top.equalTo(self.textView).offset(8)
            make.left.equalTo(self.textView).offset(5)
        }
        
    }
    

    internal func setToolBar() {
        self.view.addSubview(toolbar)
        
        toolbar.snp.makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(36)
        }
    }
    
    internal func setSelectedPicView() {
        //当一个控制器添加另外一个控制器的时候,需要先把控制器添加进来,才能添加View,否则当你添加View的时候控制器就被释放了,view也就添加不了
        self.addChildViewController(selectePicVC)
        self.view.addSubview(selectePicVC.view)
        
        selectePicVC.view.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(KScreenH / 3 * 2)
        }
        
        selectePicVC.view.isHidden = true
    }
    
}




